import { getUserInfo } from "@/core/api/my.js";
import { appauth, userinfo, getQiniuToken } from "@/core/api/index.js";
import Vue from 'vue';
import { hex_md5 } from '@/utils/md5.js'

const state = {
    userInfo: {},
    openid: ''
};

const getters = {
};

const mutations = {
    setUserInfo(state, data) {
        state.userInfo = data;
    },
    // 修正命名为驼峰式
    setOpenid(state, data) {
        state.openid = data;
    },
};

const actions = {
    async getOpenid(content) {
        try {
            // 将wx.login封装为Promise
            const res = await new Promise((resolve, reject) => {
                wx.login({
                    success: resolve,
                    fail: reject
                });
            });

            const params = {
                code: res.code
            };
            req.data.phone = ''
            const req = await appauth(params);
            uni.setStorageSync('token', req.data.token);
            
            // 正确获取openid（需要根据实际接口返回结构调整）
            if (req.data.wxinfo && req.data.wxinfo.openid) {
                content.commit('setOpenid', req.data.wxinfo.openid);
            }
            
            // 正确调用action
			if(!req.data.phone) return
            await content.dispatch('getUserinfo');
        } catch (error) {
            console.error('获取openid失败:', error);
            // 可以在这里添加错误提示给用户
        }
    },
    
    async getQiniuToken(content) {
        try {
            const { data } = await getQiniuToken();
            uni.setStorageSync('uploadToken', data.uptoken);
        } catch (error) {
            console.error('获取七牛云token失败:', error);
        }
    },
    
    async getUserinfo(content) {
        try {
            const req = await userinfo();
            console.log(req, '执行了');
            content.commit('setUserInfo', req.data);
            // 可以在这里添加需要的存储逻辑
            // uni.setStorageSync('avatar', req.data.avatar);
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
    }
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
};